using Microsoft.Extensions.Logging;
using System.Text;
using System.Text.Json;

namespace SeataNet.Core.Serialization
{
    /// <summary>
    /// JSON序列化器
    /// </summary>
    public class JsonSerializer : ISerializer
    {
        private readonly ILogger<JsonSerializer> _logger;
        private readonly JsonSerializerOptions _options;

        public JsonSerializer(ILogger<JsonSerializer> logger)
        {
            _logger = logger;
            _options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                WriteIndented = false,
                DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
            };
        }

        public SerializerType Type => SerializerType.Json;

        public byte[] Serialize<T>(T obj)
        {
            try
            {
                if (obj == null)
                {
                    return Array.Empty<byte>();
                }

                var json = System.Text.Json.JsonSerializer.Serialize(obj, _options);
                return Encoding.UTF8.GetBytes(json);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "JSON序列化失败");
                throw;
            }
        }

        public T Deserialize<T>(byte[] data)
        {
            try
            {
                if (data == null || data.Length == 0)
                {
                    return default;
                }

                var json = Encoding.UTF8.GetString(data);
                return System.Text.Json.JsonSerializer.Deserialize<T>(json, _options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "JSON反序列化失败");
                throw;
            }
        }

        public byte[] Serialize(object obj, Type type)
        {
            try
            {
                if (obj == null)
                {
                    return Array.Empty<byte>();
                }

                var json = System.Text.Json.JsonSerializer.Serialize(obj, type, _options);
                return Encoding.UTF8.GetBytes(json);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"JSON序列化失败: {type.Name}");
                throw;
            }
        }

        public object Deserialize(byte[] data, Type type)
        {
            try
            {
                if (data == null || data.Length == 0)
                {
                    return null;
                }

                var json = Encoding.UTF8.GetString(data);
                return System.Text.Json.JsonSerializer.Deserialize(json, type, _options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"JSON反序列化失败: {type.Name}");
                throw;
            }
        }
    }
}
